package com.alex.game.framework
{
	import com.unsk.util.Log;
	
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.utils.getTimer;
	
	public class BasicGame extends MovieClip
	{
		private var currentState:BasicState;
		
		public function BasicGame(state:BasicState, stage:Stage)
		{
			//Set le stage
			GG.stage = stage;
			
			//Initialize la première state
			this.currentState = state;
			GG.stage.addChild(state);
			state.create();
			
			//Temps écoulé entre chaque frame
			initElapsedTime();
			
			//Boutton pressé
			initKeys();
			
			//Démarre le timer enter frame
			GG.stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		private function initElapsedTime():void
		{
			GG.elapsedTime = getTimer();
			GG.lastTime = getTimer();
		}
		private function initKeys():void
		{
			GG.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			GG.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
		}
		private function keyDownHandler(e:KeyboardEvent):void
		{
			if(e.keyCode == Input.KEYCODE_LEFT)
				Input.KEY_LEFT = true;
			
			if(e.keyCode  == Input.KEYCODE_DOWN)
				Input.KEY_DOWN = true;
			
			if(e.keyCode == Input.KEYCODE_UP)
				Input.KEY_UP = true;
			
			if(e.keyCode == Input.KEYCODE_RIGHT)
				Input.KEY_RIGHT = true;
		}
		private function keyUpHandler(e:KeyboardEvent):void
		{
			if(e.keyCode == Input.KEYCODE_LEFT)
				Input.KEY_LEFT = false;
			if(e.keyCode  == Input.KEYCODE_DOWN)
				Input.KEY_DOWN = false;
			if(e.keyCode == Input.KEYCODE_UP)
				Input.KEY_UP = false;
			if(e.keyCode == Input.KEYCODE_RIGHT)
				Input.KEY_RIGHT = false;
		}
		private function updateElapsedTime():void
		{
			GG.elapsedTime = getTimer() - GG.lastTime;
			GG.lastTime = getTimer();
		}
		public function switchState(newState:BasicState):void
		{
			//Supprime la state actuelle
			currentState.destroy();
			GG.stage.removeChild(currentState);
			
			//Ajoute la nouvelle state
			this.currentState = newState;
			this.stage.addChild(newState);
			
			newState.create();
		}
		private function update():void
		{
			//Update la state
			this.currentState.update();
			updateElapsedTime();
		}
		private function enterFrameHandler(e:Event):void
		{
			update();
		}
	}
}